#!/usr/bin/env python
# coding=utf-8
# Author:  vavava
# Created: 04/11/2012

if __name__ == '__main__':
    """ for file debug"""
    import sys,os
    sys.path.insert(0,os.path.join( os.getcwd(), '..' ))

import pickle,time,socket
from socketserver import TCPServer,StreamRequestHandler

class BaseCommand:
    def __init__(self,name,cmd_type,data):
        self.name = name
        self.cmd_type = cmd_type
        self.data = data

    @staticmethod
    def get_msg(name,data=None):
        return pickle.dumps(BaseCommand(name,data))

    @staticmethod
    def parse(data):
        if data:
            return pickle.loads(data)

class CmdHandle:
    def __init__(self,ws,log):
        self.ws = ws
        self.log = log

    def process(self,cmd):
        if cmd == "AddWorksheep":
            self.sw.AddWorksheep(
                cmd.param.get("ws"),
                cmd.param.get("start")
            )
        elif cmd == "ActivateWorkshop":
            self.sw.ActivateWorkshop()
        elif cmd == "DeactivateWorkshop":
            self.sw.DeactivateWorkshop()
        elif cmd == "AddWork":
            self.sw.AddWork(cmd.param.get("work"))
        elif cmd == "Exec":
            exec(compile(
                cmd.param.get("src"),
                '',
                "exec"
            ))
        else:
            self.log.warn("unknown cmd:%s"%cmd)

class SerReqHandler(StreamRequestHandler):
    def __init__(self, request, client_address, server):
        StreamRequestHandler.__init__(self, request, client_address, server)
        self.log = server.log

    def setup(self):
        self.connection = self.request
        if self.timeout is not None:
            self.connection.settimeout(self.timeout)
        if self.disable_nagle_algorithm:
            self.connection.setsockopt(socket.IPPROTO_TCP,
                socket.TCP_NODELAY, True)
        self.rfile = self.connection.makefile('rb', self.rbufsize)
        self.wfile = self.connection.makefile('wb', self.wbufsize)

    def handle(self):
        data = self.rfile.read()
        cmd = BaseCommand.parse(data)
        self.log.debug("New cmd coming: %s %f"%(cmd.name,time.clock()))
        self.server.processor(cmd)

    def finish(self):
        print("finish")


class MyTCPServer(TCPServer):
    def __init__(self, processor, server_address,
                 RequestHandlerClass, bind_and_activate=True, log=None):
        TCPServer.__init__(self,server_address,
            RequestHandlerClass,bind_and_activate)
        self._processor = processor
        self.log = log

class ServerInterface:
    def __init__(self, processor, host="localhost",
                 port=4444, timeout= 30, log=None):
        self._host = host
        self._port = port
        self._timeout = timeout
        self._server = None
        self._processor = processor

    def StopServer(self):
        if self.server:
            self.server.shutdown()

    def StartServer(self):
        try:
            if self.server is None:
                self.server = MyTCPServer(
                    self._processor,
                    (self._host,self._port),
                    SerReqHandler,
                    log=self.log
                )
                self.server.timeout = self.timeout
                self.server.allow_reuse_address = True
                self.log.debug("tcp server started")
                self.server.serve_forever()
        except Exception as e:
            self.log.debug("tcp server stopped")
            self.log.exception(e)
        finally:
            if self.server:
                self.server.shutdown()
                self.server = None
